import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Divider, Drawer, Button, Radio, Modal, Input, Table, Tag, message, Spin, List, Typography, Checkbox } from 'antd';
import styles from "./index.less";
import { spawn } from 'child_process';
import zl2 from '@/assets/icons/zl2.png'
import zl1 from '@/assets/icons/zl1.png'
import zl3 from '@/assets/icons/zl3.png'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Search = Input.Search;


class AddFromP extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: '',
      mockdata: [],
      mockdataTwo: [],
      awaitList: [],
      totaltime: '',
      submitList: [],
      selectedKeys: [],
      value: '',
      page: 1,
      bc: [],
      pageSize: 500,
      log: false,
      accumulationList: [],
      selectedRowKeys: [],
      selectedRowKeysTwo: [],
    }
  }

  componentDidMount() {
    this.props.form.setFields({ "searchProblem": "" })
  }

  fetchb = () => {
    this.setState({ log: true })
    const { dispatch, currentUser } = this.props;
    const { value, page, limit } = this.state
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'extendRt/knowledgeQuestionList',
        payload: { query: value, page, limit: 500, order: 'askCount', sort: 'desc' },
        callback: res => {
          console.log('获取相似问模板列表', res);
          if (res.code === 0) {
            let temp = res.data.list
            temp.map((item, index) => { temp[index].key = index })
            this.setState({
              mockdata: temp,
              totaltime: Number(res.data.total),
              log: false
            }, () => {
            })
          }
        },
      });
    });
  }



  batchAdd = () => {
    const { awaitList, mockdataTwo } = this.state
    let merge = [...awaitList, ...mockdataTwo]
    let temp = [];
    for (let i = 0; i < merge.length; i++) {
      if (temp.indexOf(merge[i].question) == -1) {
        temp.push(merge[i].question);
      }
    }
    console.log(temp)
    let list = []
    temp.map((item) => {
      let obj = {}
      obj.question = item
      list.push(obj)
    })
    this.setState({ awaitList: list, selectedRowKeys: [] })
  }


  add = (item) => {
    console.log(item)
    this.setState({selectedRowKeys: []})
    const { awaitList } = this.state
    let a = {}
    a.question = item.question
    awaitList.push(a)
    let temp = [];
    for (let i = 0; i < awaitList.length; i++) {
      if (temp.indexOf(awaitList[i].question) == -1) {
        temp.push(awaitList[i].question);
      }
    }
    let list = []
    temp.map((item, index) => {
      let obj = {}
      obj.question = item
      obj.key = index
      list.push(obj)
    })
    console.log(list)
    this.setState({ awaitList: list })
  }

  remove = (item) => {
    const { awaitList } = this.state
    console.log(awaitList.filter(val => val.question != item))
    this.setState({ awaitList: awaitList.filter(val => val.question != item) })
    this.setState({selectedRowKeysTwo: [] })
  }

  batchRemove = () => {
    const { awaitList, submitList } = this.state
    console.log(awaitList, submitList)
    for (let i = 0; i < submitList.length; i++) {
      for (let j = 0; j < awaitList.length; j++) {
        if (awaitList[j].question == submitList[i].question) {
          awaitList.splice(j, 1)
        }
      }
    }
    console.log(awaitList);
    this.setState({ awaitList, selectedRowKeys: [],selectedRowKeysTwo: [] })
  }

  submitknowledge = () => {
    const { awaitList } = this.state
    // console.log(awaitList)
    if(awaitList.length){
      let arr = []
      awaitList.map((item)=>{
       arr.push(item.question.replace(/<[^>]+>/g,""))
      })
      console.log(arr)
      this.props.addQuestions(arr)
      this.setState({awaitList:[],selectedRowKeysTwo:[],selectedRowKeys:[]})
    }else{
      message.error('添加项为空')
    }
  }





  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        xs: 24,
        sm: 2
      },
      wrapperCol: {
        xs: 24,
        sm: 22
      }
    }
    const { selectedRowKeys, selectedRowKeysTwo,submitList } = this.state;
    console.log(selectedRowKeysTwo,'----------selectedRowKeysTwo')
    const  arr = [];
    for(let i of submitList){
      arr.push(i.question)
    }
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(selectedRowKeys, 'selectedRows: ', selectedRows);
        let list = []
        selectedRows.map((item, index) => {
          let obj = {}
          obj.question = item.question
          obj.key = index
          list.push(obj)
        })
        console.log(list)
        this.setState({ selectedRowKeys, mockdataTwo: list })
      },
    };
    const rowSelectionTwo = {
      selectedRowKeys:selectedRowKeysTwo,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(selectedRowKeys, 'selectedRows: ', selectedRows);
        this.setState({ selectedRowKeysTwo:selectedRowKeys, submitList: selectedRows })
      },
      // getCheckboxProps: record => ({
      //   checked: (arr.indexOf(record.question)>-1?true:false)
      // }),
    };
    const columns = [
      {
        title: () => {
          return (
            <div>
              <span>问题库</span>
              <Button onClick={this.batchAdd} size='small' style={{ float: 'right' }}>批量添加</Button>
            </div>
          )
        },
        width: 'calc(100vw)',
        fixed: 'left',
        align: 'left',
        dataIndex: 'question',
        render: (question, val) => {
          return <div className={styles.listPb}>
            <span dangerouslySetInnerHTML={{ __html: question }} className={styles.ellipsisB} style={{ width: 380 }}>
            </span>
            <img style={{ marginLeft: 10 }} onClick={() => { this.add(val) }} src={zl2} />
          </div>
        }
      },
    ]
    const columnsTwo = [
      {
        title: () => {
          return (
            <div>
              <span>待添加</span>
              <Button onClick={this.batchRemove} size='small' style={{ float: 'right' }}>批量移除</Button>
            </div>
          )
        },
        width: 'calc(100vw)',
        fixed: 'left',
        align: 'left',
        dataIndex: 'question',
        render: (question, val) => {
          return <div className={styles.listPb}>
            <span dangerouslySetInnerHTML={{ __html: question }} className={styles.ellipsisB} style={{ width: 380 }}>
            </span>
            <img style={{ marginLeft: 10 }} onClick={() => { this.remove(question) }} src={zl3} />
          </div>
        }
      },
    ]
    return (
      <div>
        {getFieldDecorator('searchProblem', {
          initialValue: '',
        })(
          // this.props.form.setFields({ "searchProblem": "" })
          <Search
            style={{ width: 300 }}
            placeholder="请输入搜索内容"
            onSearch={value => {
              if (value == '') {
                this.setState({ value: '囘囙囜囝回囟囡団囤囥囦囧囨囩囱囫囬囮囯困囱囲図囵囶囷囸囹囻囼图囿圀圁圂圂圃圄圅圆囵', page: 1, totaltime: 0, selectedKeys: [], }, () => {
                  this.fetchb()
                })
              } else {
                this.setState({ value, page: 1, totaltime: 0, selectedKeys: [], }, () => {
                  this.fetchb()
                })
              }
            }}
          />
        )}
        <Spin spinning={this.state.log}>
          <Row style={{ marginTop: 20 }} gutter={0}>
            <Col style={{maxWidth:500}} span={11}>
              <div  className={styles.bk}>
                <div className='listZdy'>
                  <Table
                    scroll={{ y: 544 }}
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={this.state.mockdata}// 数据
                    pagination={false}
                  />
                </div>
              </div>
            </Col>
            <Col className={styles.imgJz} span={2}>
              <img src={zl1} />
            </Col>
            <Col style={{maxWidth:500}} span={11}>
              <div  className={styles.bk}>
                <div className='listZdy'>
                  <Table
                    scroll={{ y: 544 }}
                    rowSelection={rowSelectionTwo}
                    columns={columnsTwo}
                    dataSource={this.state.awaitList}// 数据
                    pagination={false}
                  />
                </div>
              </div>
            </Col>
          </Row>
        </Spin>
        {/* <Button style={{marginLeft:10}}  onClick={this.submitknowledgeCancel} style={{ marginLeft: 20 }}>取消</Button> */}
        <span>注：请先搜索内容再添加问题到知识点</span>
        <div style={{ marginRight: 50 }} className='zdyButtonA'><Button type='primary' onClick={this.submitknowledge} style={{ marginTop: 20 }}>添加到知识点</Button> </div>
      </div>
    );
  }




}
export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(AddFromP));

